from django.shortcuts import render
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.views import View


# Create your views here.
@method_decorator(csrf_protect, name="dispatch")
@method_decorator(login_required, name="dispatch")
class UploadView(View):
    def post(self, request, *args, **kwargs):
        if 'file' not in request.FILES:
            return JsonResponse({"error": "文件未上传"}, status=400)

        uploaded_file = request.FILES['file']

        file_path = f"/tmp/app{kwargs["app_id"]}_{uploaded_file.name}"
        with open(file_path, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)

        return JsonResponse({'status': 'success', 'filename': uploaded_file.name}, status=200)

    def get(self, request, *args, **kwargs):
        return render(request, template_name="home.html")


def index_view(request):
    return render(request, template_name="process2.html")
